import { useUserStore } from '@/stores/index'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import router from '@/router'
// const baseURL = 'http://big-event-vue-api-t.itheima.net'
const baseURL = 'http://127.0.0.1:3007'

const instance = axios.create({
  // 1.基础地址，超时时间
  baseURL,
  timeout: 100000
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.status === 0) {
      return res.data
    }
    ElMessage({ message: res.data.message || '服务异常', type: 'error' })
    return Promise.reject(res.data)
  },
  (err) => {
    ElMessage({
      message: err.response.data.message || '服务异常',
      type: 'error'
    })
    console.log(err)
    if (err.response.status === 401) {
      router.push('/login')
    }
    return Promise.reject(err)
  }
)
// 将网络图片地址转换为File对象
const imageUrlToFile = async (url, fileName) => {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: 'image/jpeg'
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    // eslint-disable-next-line no-unused-vars
    return new Promise((resolve, reject) => {
      resolve(file)
    })
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}

export default instance
export { baseURL, imageUrlToFile }
